package com.group3.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group3.dao.LeaveDetailMapper;
import com.group3.dao.LeaveMapper;
import com.group3.dao.LeaveOperationRecordMapper;
import com.group3.domain.*;
import com.group3.exception.BusinessException;
import com.group3.exception.ExceptionEnum;
import com.group3.pojo.receive.LeaveReceive;
import com.group3.pojo.result.LeaveDetailResult;
import com.group3.service.TeacherLeaveService;
import com.group3.utils.NotNull;
import com.group3.utils.Result;
import com.group3.utils.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * TeacherLeaveServiceImpl
 *
 * @author HY, PX
 * 2021/06/10 16:52
 **/


@Service
public class TeacherLeaveServiceImpl implements TeacherLeaveService {
    @Resource
    private LeaveDetailMapper leaveDetailMapper;
    @Resource
    private LeaveMapper leaveMapper;
    @Resource
    private LeaveOperationRecordMapper leaveOperationRecordMapper;

    @Override
    public Result<List<LeaveDetail>> selectLeave(LeaveReceive leaveReceive) {
      LeaveDetail leaveDetail = new LeaveDetail();

        LeaveDetailExample leaveDetailExample = new LeaveDetailExample();
        LeaveDetailExample.Criteria criteria = leaveDetailExample.createCriteria();

//        判断提交时间是否在时间段中
        if (NotNull.judge(leaveReceive.getStartTime())) {
            criteria.andSubmitTimeLessThan(leaveReceive.getStartTime());
        }
        if (NotNull.judge(leaveReceive.getEndTime())) {
            criteria.andSubmitTimeGreaterThan(leaveReceive.getEndTime());
        }

        if (NotNull.judge(leaveReceive.getProfessionName())) {
            criteria.andProfessionNameEqualTo(leaveReceive.getProfessionName());
        }
        if (NotNull.judge(leaveReceive.getDepartName())) {
            criteria.andDepartNameEqualTo(leaveReceive.getDepartName());
        }
        if (NotNull.judge(leaveReceive.getGrade())) {
            criteria.andGradeEqualTo(leaveReceive.getGrade());
        }
        if (NotNull.judge(leaveReceive.getClassId())) {
            criteria.andClassIdEqualTo(leaveReceive.getClassId());
        }
        if (NotNull.judge(leaveReceive.getStudentId())) {
            criteria.andStudentIdEqualTo(leaveReceive.getStudentId());
        }
        if (NotNull.judge(leaveReceive.getStudentName())) {
            criteria.andStudentNameLike("%"+(leaveReceive.getStudentName())+"%");
        }
        if (NotNull.judge(leaveReceive.getTheme())) {
            criteria.andThemeLike("%"+(leaveReceive.getTheme())+"%");
        }
        if (NotNull.judge(leaveReceive.getType())) {
            criteria.andTypeEqualTo(leaveReceive.getType());
        }

//        判断是否是未审批的，未审批：”0“，其他都大于0，用于前端分状态
        if (leaveReceive.getState() == 0){
            criteria.andStateEqualTo(0);
        }else {
            criteria.andStateGreaterThan(0);
        }
//        1.先开启分页
        PageHelper.startPage(leaveReceive.getPageNumber(), leaveReceive.getPageSize());//启动分页
//        2.执行SQL语句
        List<LeaveDetail> leaveDetails = leaveDetailMapper.selectByExample(leaveDetailExample);
//        3.获取分页信息
        PageInfo<LeaveDetail> leaveResultsPageInfo = new PageInfo<>(leaveDetails);//获取分页信息

//        4.返回查询信息
        return ResultUtil.success("查询成功", leaveDetails, leaveResultsPageInfo.getTotal());
    }


    @Override
    public Result selectLeaveByLeaveId(Integer leaveId) {

        LeaveDetailExample leaveDetailExample = new LeaveDetailExample();
        LeaveDetailExample.Criteria criteria = leaveDetailExample.createCriteria();

        criteria.andLeaveIdEqualTo(leaveId);
        //TODONE  自己改一哈好，身份验证
//        List<LeaveDetail> leaveDetails = leaveDetailMapper.selectByExample(leaveDetailExample);
        List<LeaveDetailResult> leaveDetailResults = leaveDetailMapper.SelectLeaveInfo(leaveDetailExample);

        if (leaveDetailResults == null){
            throw new BusinessException(ExceptionEnum.DATABASE_OPERATION_ERR);
        }
        return ResultUtil.success("查询成功", leaveDetailResults);
    }


    @Override
    public Result processingLeaves(List<Integer> leaveIds, Integer state) {
//        todo：没有测试，吃完饭回来看          xhy:所以看了嘛？
        Date currentTime = new Date();
        int res;
        Leave leave = new Leave();
//        遍历请假id-》将请假状态修改
        for (Integer leaveId : leaveIds) {
            leave.setState(state);

            LeaveExample leaveExample = new LeaveExample();
            LeaveExample.Criteria criteria = leaveExample.createCriteria();
            criteria.andLeaveIdEqualTo(leaveId);
//            验证是否是请假不通过,请假不通过给LeaveOperationRecord数据库的表添加新值
            if (state == 1){
                LeaveOperationRecord leaveOperationRecord = new LeaveOperationRecord();
                leaveOperationRecord.setLeaveId(leaveId);
                leaveOperationRecord.setOperationTime(currentTime);
                res = leaveOperationRecordMapper.insertSelective(leaveOperationRecord);
//                判断是否在数据库新增成功
                if (res <= 0){
                    return ResultUtil.error("添加请假操作失败");
                }
            }
//          修改leave表中的状态
            res = leaveMapper.updateByExampleSelective(leave, leaveExample);

            if (res <= 0) {
                return ResultUtil.error("修改失败");
            }
        }
        return ResultUtil.error("修改成功");
    }

    @Override
    public Result processingLeaveNo(Integer leaveId, String reasons_failure) {
        int res;
//        修改leave对象的状态将状态转化成未通过“1”
        Leave leave = new Leave();
        leave.setState(1);

//        获取数据库leave表中的leaveId
        LeaveExample leaveExample = new LeaveExample();
        leaveExample.createCriteria().andLeaveIdEqualTo(leaveId);
        //更新请假对的状态
        res = leaveMapper.updateByExampleSelective(leave, leaveExample);

//        状态修改成功后将原因添加进数据库（当原因不为空）
        if (res > 0 && reasons_failure != null) {
            LeaveOperationRecord leaveOperationRecord = new LeaveOperationRecord();
            leaveOperationRecord.setLeaveId(leaveId);
            leaveOperationRecord.setReasonsFailure(reasons_failure);
            //        获取当前时间类型为date
            Date currentTime = new Date();
            leaveOperationRecord.setOperationTime(currentTime);
//            对数据库表中的leaveOperationRecord添加新数据
            res = leaveOperationRecordMapper.insertSelective(leaveOperationRecord);

        }
        return res > 0 ? ResultUtil.success("修改成功") : ResultUtil.error("修改失败");
    }


}
